package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.UserDao;
import com.foreknow.elm.dao.impl.UserDaoImpl;
import com.foreknow.elm.po.User;
import com.foreknow.elm.service.UserService;
import com.foreknow.elm.util.DBUtil;

/**
 * @author 啊滨
 * @date 2023/2/14 10:08
 */
public class UserServiceImpl implements UserService {
    @Override
    public User getUserByIdByPass(String userId, String password){
        User user=new User();
        try {
            UserDao userDao=new UserDaoImpl();
            DBUtil.getConnection();
            user  = userDao.getUserByIdByPass(userId, password);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return user;
    }

    @Override
    public int getUserById(String userId) {
        int count=0;
        try {
            UserDao userDao=new UserDaoImpl();
            DBUtil.getConnection();
            count=userDao.getUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return count;
    }

    @Override
    public int saveUser(String userId,String password,String userName,Integer userSex) {
        int isRight=0;
        try {
            DBUtil.getConnection();
            //开启一个事务
            DBUtil.beginTransaction();
            UserDao userDao=new UserDaoImpl();
            //调用dao查询用户是否存在，如果不存在调用添加
            int count = userDao.getUserById(userId);
            if (count==0){
                isRight = userDao.saveUser(userId,password,userName,userSex);
            }
            DBUtil.commitTransaction();//提交一个事务


        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();//回滚一个事务
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            DBUtil.close();//关闭connection
        }
        return isRight;
    }
}
